import 'package:flutter/material.dart';
import 'dart:io';
import 'package:window_manager/window_manager.dart';

/// 自定义标题栏
/// 仅包含关闭和最小化按钮
class CustomTitleBar extends StatelessWidget {
  const CustomTitleBar({
    super.key,
    this.title = '',
    this.backgroundColor,
    this.height = 40.0,
  });

  final String title;
  final Color? backgroundColor;
  final double height;

  @override
  Widget build(BuildContext context) {
    // 只在 Windows 和 Linux 上显示自定义标题栏
    // macOS 使用原生标题栏
    if (!Platform.isWindows && !Platform.isLinux) {
      return const SizedBox.shrink();
    }

    final theme = Theme.of(context);
    final isDark = theme.brightness == Brightness.dark;
    
    return Container(
      height: height,
      decoration: BoxDecoration(
        color: backgroundColor ?? (isDark ? Colors.grey[900] : Colors.white),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.1),
            offset: const Offset(0, 1),
            blurRadius: 2,
          ),
        ],
      ),
      child: Row(
        children: [
          // 左侧：应用图标和标题
          Padding(
            padding: const EdgeInsets.only(left: 12.0),
            child: Row(
              children: [
                Icon(
                  Icons.rocket_launch,
                  size: 18,
                  color: theme.primaryColor,
                ),
                if (title.isNotEmpty) ...[
                  const SizedBox(width: 8),
                  Text(
                    title,
                    style: TextStyle(
                      fontSize: 13,
                      fontWeight: FontWeight.w500,
                      color: isDark ? Colors.white : Colors.black87,
                    ),
                  ),
                ],
              ],
            ),
          ),
          
          // 中间：可拖动区域
          Expanded(
            child: GestureDetector(
              behavior: HitTestBehavior.translucent,
              onPanStart: (details) {
                windowManager.startDragging();
              },
              onDoubleTap: () {
                // 双击标题栏不做任何操作（不最大化）
              },
              child: Container(),
            ),
          ),
          
          // 右侧：窗口控制按钮
          _buildMinimizeButton(context),
          _buildCloseButton(context),
        ],
      ),
    );
  }

  /// 最小化按钮
  Widget _buildMinimizeButton(BuildContext context) {
    return _WindowButton(
      icon: Icons.remove,
      tooltip: '最小化',
      onPressed: () {
        windowManager.minimize();
      },
      hoverColor: Colors.grey.withOpacity(0.2),
    );
  }

  /// 关闭按钮
  Widget _buildCloseButton(BuildContext context) {
    return _WindowButton(
      icon: Icons.close,
      tooltip: '关闭',
      onPressed: () {
        windowManager.close();
      },
      hoverColor: Colors.red.withOpacity(0.8),
      iconColorOnHover: Colors.white,
    );
  }
}

/// 窗口按钮组件
class _WindowButton extends StatefulWidget {
  const _WindowButton({
    required this.icon,
    required this.onPressed,
    this.tooltip,
    this.hoverColor,
    this.iconColorOnHover,
  });

  final IconData icon;
  final VoidCallback onPressed;
  final String? tooltip;
  final Color? hoverColor;
  final Color? iconColorOnHover;

  @override
  State<_WindowButton> createState() => _WindowButtonState();
}

class _WindowButtonState extends State<_WindowButton> {
  bool _isHovered = false;

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final isDark = theme.brightness == Brightness.dark;
    
    final defaultIconColor = isDark ? Colors.white70 : Colors.black54;
    final iconColor = _isHovered && widget.iconColorOnHover != null
        ? widget.iconColorOnHover!
        : defaultIconColor;

    Widget button = MouseRegion(
      onEnter: (_) => setState(() => _isHovered = true),
      onExit: (_) => setState(() => _isHovered = false),
      child: Material(
        color: _isHovered 
            ? (widget.hoverColor ?? Colors.grey.withOpacity(0.2))
            : Colors.transparent,
        child: InkWell(
          onTap: widget.onPressed,
          child: Container(
            width: 46,
            height: 40,
            alignment: Alignment.center,
            child: Icon(
              widget.icon,
              size: 16,
              color: iconColor,
            ),
          ),
        ),
      ),
    );

    if (widget.tooltip != null) {
      button = Tooltip(
        message: widget.tooltip!,
        waitDuration: const Duration(milliseconds: 500),
        child: button,
      );
    }

    return button;
  }
}